#!/bin/bash
tag=$1
action=$2
hiddenSpace=99
# hiddenSpace=special:hidden

activeWorkspace=$(hyprctl -j activeworkspace|jq '.id')

toggle_client(){
    clientWorkspace=$(echo $1 |jq '.workspace.id')
    address=$(echo $1 |jq -r '.address')
    cmd=""
    if ! $(echo $1|jq '.floating');then
        cmd="$cmd;dispatch setfloating address:$address"
        cmd="$cmd;dispatch centerwindow address:$address"
        # hyprctl dispatch togglefloating tag:$tag
    fi
    if [[ $activeWorkspace == $clientWorkspace ]];then
        cmd="dispatch movetoworkspacesilent $hiddenSpace,address:$address"
    else
        cmd="$cmd;dispatch movetoworkspace $activeWorkspace,address:$address"
        cmd="$cmd;dispatch focuswindow address:$address"
        cmd="$cmd;dispatch alterzorder top,address:$address"
    fi
    hyprctl --batch $cmd
}

toggle(){
    client=$(hyprctl -j clients|jq '.[]|select(.tags|index("'"$tag"'")>=0)')
    if [[ -z "$client" ]];then
        if [[ "$tag" == "filemanager" ]];then
            filemanager
            return
        fi
        if [[ "$tag" == "obsidian" ]];then
            obsidian
            return
        fi
        return
    fi
    toggle_client "$client"
}

kitty(){
    client=$(hyprctl -j clients|jq '.[]|select(.class=="kitty" and .title=="scratchpad_term")')
    if [[ -z "$client" ]];then
        hyprctl dispatch exec "[float]" "kitty -T scratchpad_term"
        return
    fi
    toggle_client "$client"
}

filemanager(){
    client=$(hyprctl -j clients|jq '.[]|select(.class=="org.gnome.Nautilus")')
    if [[ -z "$client" ]];then
        hyprctl dispatch exec "[float]" nautilus
        return
    fi
    toggle_client "$client"
    address=$(echo $client |jq -r '.address')
    cmd="dispatch tagwindow $tag address:$address"
    hyprctl --batch $cmd
}

filemanager2(){
    client=$(hyprctl -j clients|jq '.[]|select(.class=="nemo")')
    if [[ -z "$client" ]];then
        hyprctl dispatch exec "[float]" nemo
        return
    fi
    toggle_client "$client"
    address=$(echo $client |jq -r '.address')
    cmd="dispatch tagwindow $tag address:$address"
    hyprctl --batch $cmd
}

obsidian(){
    client=$(hyprctl -j clients|jq '.[]|select(.class=="obsidian")')
    if [[ -z "$client" ]];then
        hyprctl dispatch exec "[float;size 75% 75%]" obsidian
        return
    fi
    toggle_client "$client"
    address=$(echo $client |jq -r '.address')
    cmd="dispatch tagwindow $tag address:$address"
    hyprctl --batch $cmd
}

if [[ "$tag" == "kitty" ]];then
    kitty
    return
fi


case $action in 
    "toggle") 
    toggle
    ;;
    "move") 
    hyprctl dispatch tagwindow $tag
    ;;
esac

